<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
            * {
                margin: 0;
                padding: 0
            }    
            img {
                width: 200px;
                padding: 20px;
            }    
            #parent {
                margin-left: auto;
                margin-right: auto;
                position: relative;
                width: 240px;
                border: 1px solid #333;
            }
            #fade {
                width: 100%;
                height: 100%;
                position: absolute;
                background:pink;
                opacity: 0.3;
                left: 0;
                top: 0;
            }
        </style>
    </head>
    <body>
        <div id="parent">
            <img src="images/fade.png" alt="">
            <div id="fade"></div>
        </div>
        <script>
            var parent = document.getElementById("parent");
            var fade = document.getElementById("fade");
            var opacity = getComputedStyle(fade).opacity * 100;
            var timer;
            // 使用定时器做动画
            /*
            1.执行事件时首先清除定时器
            2.定时器中的内容,用if-else 
             */
            parent.onmouseover = function () {
                clearInterval(timer);
                timer = setInterval(function () {
                    if (opacity > 70) {
                        clearInterval(timer)
                    } else {
                        opacity += 2;
                        fade.style.opacity = opacity / 100;
                    }
                }, 50)
            }
            parent.onmouseout = function () {
                clearInterval(timer);
                timer = setInterval(function () {
                    if (opacity < 30) {
                        clearInterval(timer)
                    } else {
                        opacity -= 2;
                        fade.style.opacity = opacity / 100;
                    }
                }, 50)
            }
        </script>
    </body>
    </html>